package com.sbm.datasource.dynamic;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sbm.datasource.config.MyBatisConfig;

@Configuration
public class DynamicMapperScan {
	private static final Logger LOGGER = LoggerFactory.getLogger(DynamicMapperScan.class);

	/**
	 * MapperScannerConfigurer实现了BeanDefinitionRegistryPostProcessor接口
	 * 为了向mapperScannerConfigurer注入MyBatisConfig对象
	 * (MapperScannerConfigurer加载时,一般Bean没有加载,无法使用普通Bean定义方法注入)
	 * MyBatisConfig必须同样实现BeanDefinitionRegistryPostProcessor接口
	 * BeanDefinitionRegistryPostProcessor接口使得实现Bean在其他一般Bean(@Component或@Bean)之前加载
	 * @return
	 */
	@Bean
	public MyBatisConfig getBaseConfig(){
		return new MyBatisConfig();
	}

	/**
	 * 必须使用@Autowired注入MyBatisConfig(实现BeanDefinitionRegistryPostProcessor接口)
	 * @param mybatis
	 * @return
	 */
	@Bean
	@Autowired
	public MapperScannerConfigurer mapperScannerConfigurer(MyBatisConfig mybatis) {
		LOGGER.info("————Mapper映射扫描————");
		String basePackage = mybatis.getMapperScanPackage();
		LOGGER.info("映射路径：" + basePackage);
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setSqlSessionFactoryBeanName("DynamicSqlSessionFactory");
		mapperScannerConfigurer.setBasePackage(basePackage);
		return mapperScannerConfigurer;
	}
}
